package com.smart.rpc.hessian;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.remoting.caucho.HessianServiceExporter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.smart.rpc.annotation.HessianService;

public class HessainServiceExporter implements BeanFactoryPostProcessor {

	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
		Map<String, Object> beans = beanFactory.getBeansWithAnnotation(HessianService.class);
		if (beans != null && !beans.isEmpty()) {
			Iterator<Entry<String, Object>> iterator = beans.entrySet().iterator();
			while (iterator.hasNext()) {
				Entry<String, Object> entry = iterator.next();
				Class<?> clazz = entry.getValue().getClass();
				HessianService service = clazz.getAnnotation(HessianService.class);
				String serviceName = service.value();
				Class<?>[] interfaces = clazz.getInterfaces();
				
				Class<?> intfClazz = interfaces[0];
				
				if(!intfClazz.isInterface()){
					continue;
				}
				
				System.out.println("beanName : " + entry.getKey());
				if(StringUtils.isEmpty(serviceName)){
					serviceName = "/".concat(intfClazz.getSimpleName());
				}else if(!serviceName.startsWith("/")){
					serviceName = "/".concat(serviceName);
				}
				System.out.println("serviceName : " + serviceName);
				
				if(!beanFactory.containsSingleton(serviceName)){
					HessianServiceExporter hessianServiceExporter = new HessianServiceExporter();
					hessianServiceExporter.setServiceInterface(intfClazz);
					hessianServiceExporter.setService(entry.getValue());
					hessianServiceExporter.afterPropertiesSet();
					beanFactory.registerSingleton(serviceName, hessianServiceExporter);
				}

			}
		}
	}
}
